import { defineStore } from "pinia";
import UserApi from "../api/user";

export const useUserStore = defineStore("user", {
  state: () => {
    return {
      isLogin: false,
      isAdmin: false,
      userData: {},
    };
  },
  getters: {},
  actions: {
    loginState(userData) {
      this.isLogin = true;
      this.userData = userData;
      if (userData && userData.role === 1) {
        this.isAdmin = true;
      }
    },
    logoutState() {
      this.isLogin = false;
      this.isAdmin = false;
      this.userData = {};
    },
    async isAuth() {
      if (this.userData) {
        const api = new UserApi();
        let res = await api.find(this.userData.userId);
        if (res.code === 401 || res.code === 403) {
          this.isLogin = false;
          this.isAdmin = false;
          this.userData = {};
        }
        if (res.code === 200 && res.data.role !== 1) {
          this.isAdmin = false;
        }
      } else {
        this.isLogin = false;
        this.isAdmin = false;
        this.userData = {};
      }
    },
  },
  persist: true,
});
